
//Stolen and slightly modified from Peter Paul Koch:
//http://www.quirksmode.org/dom/cms.html

function CellEditor(e) {

    if (!document.getElementById || !document.createElement) return;
    if (!e) var obj = window.event.srcElement;
    else var obj = e.target;
    while (obj.nodeType != 1) {
	obj = obj.parentNode;
    }
    if (obj.tagName == 'TEXTAREA' || obj.tagName == 'A') return;
    while (obj.nodeName != 'TD' && obj.nodeName != 'HTML') {
	obj = obj.parentNode;
    }

    if (obj.nodeName == 'HTML') return;

    var extant_text = obj.innerHTML;
    obj.innerHTML = "";
    obj.originalText = extant_text;
    var new_text_area = document.createElement('TEXTAREA');
    new_text_area.onblur = cellEditorBlurBroker;
    obj.appendChild(new_text_area);
    new_text_area.value = extant_text;

    new_text_area.focus();

}

function cellEditorBlurBroker(e){
    if (!document.getElementById || !document.createElement) return;
    if (!e) var obj = window.event.srcElement;
    else var obj = e.target;
    var cell = obj.parentNode;
    changeBorderOnDifference(obj);
    saveEditToCell(obj);
    saveEditToRun(cell);

}
function changeBorderOnDifference(obj){
    var cell = obj.parentNode;
    var originalText = cell.originalText;
    var newText = obj.value;
    if( originalText != newText ){
	cell.className = "cellEdited";
    }
}
function saveEditToRun(cell){

    var Element = cell.runElement;
    var text = cell.firstChild;
    Element[0].firstChild.data = text.data;
    Element[0].className = cell.className;
}


function saveEditToCell(obj) {

    area = obj;
    parent = area.parentNode;
    while (parent.nodeName != 'TD' && parent.nodeName != 'HTML') {
	parent = parent.parentNode;
    }

    new_text_node=document.createTextNode( area.value );
    parent.removeChild(area);
    parent.appendChild(new_text_node);

}
